package ntd.util.frame.action.ai;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.dahuatech.hutool.core.collection.CollUtil;
import com.modular.extra.ai.FactoryAiOpt;
import ntd.action.ActionAbs;
import ntd.action.bo.ActionInfo;
import ntd.action.bo.ActionOutBo;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.data.factory.FactoryData;
import ntd.util.frame.javacv.action.bean.VisionModelDo;
import ntd.util.frame.javacv.tool.ToolAiUserSites;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActionAiTrend extends ActionAbs {

    @Override
    public ActionInfo info() {
        return new ActionInfo("AI趋势", "ai-trend", new ActionAiTrend());
    }

    private static Map<String, String> map = new HashMap<>();

    static {
        map.put("Water", "waterCount");
        map.put("VehicleType", "vehicleTypeCount");
        map.put("Algae", "algaeCount");
        map.put("WaterGarbage", "waterGarbageCount");
        map.put("Person", "personCount");
    }

    @Override
    public ActionOutBo handle() {
        //获取视频实时流，参数模型类型、摄像头编码
        // 执行逻辑
        String mn = actionInBo.getParamStr("mn");

        //验证参数
        if (StrUtil.isEmpty(mn)){
            throw new ComException("请选择站点编号");
        }else {
            //验证站点是否存在
            if (!ToolAiUserSites.IsExistMn(mn)){
//                throw new ComException("没有该站点的权限，请联系管理员！");
            }
        }

        //数据库
        Db use = Db.use(FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c"));

        String sql = "SELECT COUNT(*) AS num,ai_mode_type,DATE_FORMAT(analytics_time, '%Y-%m-%d') AS date FROM airesult WHERE isAlert = 1 AND siteMn= ? AND DATE_SUB(CURDATE(), INTERVAL 6 DAY) <= DATE(analytics_time) \n" +
                "GROUP BY ai_mode_type,DATE_FORMAT(analytics_time, '%Y-%m-%d')";

        List<Entity> result = null;
        try {
            result = use.query(sql,mn);
        } catch (SQLException e) {
            StaticLog.error(e, "[AI][趋势查询][{}]失败...");
        }

        //生成七天的日期
        List<String> dateList = new ArrayList<>();
        for (int i = 6;i >= 0;i--){
            dateList.add(DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -i),"yyyy-MM-dd"));
        }
//        StaticLog.info("=="+dateList.toString());

        List<Map<Object,Object>> dataList = new ArrayList<>();

        for (String date:dateList){
            Map<Object,Object> resultMap = new HashMap<>();
            resultMap.put("date",date);

            Map<String,Integer> countMap = new HashMap<>();
            List<Entity> filter = CollectionUtil.filter(CollUtil.newArrayList(result), entity -> StrUtil.equals(date, entity.getStr("date")));
            Map<String, Entity> map = CollStreamUtil.toIdentityMap(filter, entity -> entity.getStr("ai_mode_type"));

            for (VisionModelDo visionModelDo : FactoryAiOpt.OPT_VISION_MODEL.cacheListAll()) {
                countMap.put(StrUtil.lowerFirst(visionModelDo.getCode()) + "Count", getNum(map, visionModelDo));
            }

            resultMap.put("data",countMap);

            dataList.add(resultMap);
        }

        return new ActionOutBo(dataList);
    }

    private static Integer getNum(Map<String, Entity> map, VisionModelDo visionModelDo) {
        return ObjectUtil.defaultIfNull(
                map.get(visionModelDo.getCode()), defaultEntity()).getInt("num");
    }

    private static Entity defaultEntity() {
        return new Entity().set("num", 0);
    }

    public static void main(String[] args) {
        FactoryData.dataSource("272ab1b9c5cc4ea2b76302238247284c");
    }
}
